/* eslint-disable no-plusplus */
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Divider, Button, Modal, Form, Input, Row, Col, Select, Checkbox, Upload, Icon, DatePicker, Table, Card, Popconfirm, message} from 'antd';
// import { queryRule } from './service';
import *as XLSX from 'xlsx';
import { connect } from 'dva';
import moment from 'moment'
import styles from './style.less';
import IconFont from '../../components/Icon';


import AddRecord from './components/addRecord'
import CreateIntroduce from './components/createIntroduce'
import ConfirmIntroduce from './components/confirmIntroduce'
import CheckIntroduce from './components/checkIntroduce'


import PublicTableWrapper from '@/components/TableForm'



@connect(({ home, visitrecordandtable }) => ({
    home,
    visitrecordandtable
}))

// eslint-disable-next-line react/prefer-stateless-function
class Management extends Component {
    state = {
        // 表格的头
        columns: [
            {
              title: '序号',
              dataIndex: 'number',
              width: 50,
            },
            {
              title: '走访日期',
              dataIndex: 'date',
              // eslint-disable-next-line radix
              render: text => <span>{moment(parseInt(text)).format("YYYY-MM-DD")}</span>,
            },
            {
              title: '走访街道',
              dataIndex: 'street',
              width: 100,
            },
            {
              title: '企业名称',
              dataIndex: 'name',
            },
            {
              title: '机构代码',
              dataIndex: 'code',
              align: 'center',
              width: 100,
            },
            {
              title: '走访领导',
              dataIndex: 'leader',
            },
            {
              title: '职务',
              dataIndex: 'job',
              width: 90,
            },
            {
              title: '随行人员',
              dataIndex: 'follow',
              width: 140,
              render: record => (<span>{record.join('、')}</span>)
            },
            {
              title: '服务简讯',
              dataIndex: 'introduce',
              align: 'center',
              render: (_, record) => {
                  if ( record.introduceDetails ) {
                    return (
                          <Button
                            style={{ color: '#8691fd', borderColor: '#8691fd', padding: '0px 5px' }}
                            onClick={() => this.showCheckIntdModal(record)}
                        >查看简讯</Button>
                      )
                  } 
                    return (
                        <Button
                            style={{ backgroundColor: '#8691fd', color: '#fff', borderColor: '#8691fd', padding: '0px 5px' }}
                            onClick={() => this.showAddIntdModal(record)}
                        >创建简讯</Button>
                    )
              },
            },
            {
              title: '操作',
              dataIndex: 'option',
              valueType: 'option',
              align: 'center',
              width: 110,
              render: (_, record, index) => (
                <>
                    <a onClick={() => {
                        // eslint-disable-next-line no-console
                        console.log(record)
                    }}>
                    编辑
                    </a>
                    <Divider type="vertical" />
                    <Popconfirm
                        title="你确定要删除吗？"
                        onConfirm={() => this.handleDelect(_, record, index)}
                        okText="是"
                        cancelText="否"
                    >
                        <a href="#">删除</a>
                    </Popconfirm>
                </>
              ),
            },
        ],
        // 所有弹窗的状态
        addVisible: false,
        addIntdVisible: false,
        checkIntdVisible: false,
        confirmIntdVisible: false,
        // 简讯状态 true 编辑 false 新增  true时有个key保存key值
        introduceStatus: false,
        // 简讯状态 true时的key
        introduceKey: '',
        // 简讯详情内容
        introduceDetails: {},
        // 搜索表展开收起
        expand: false,
        // 检查表格选择项
        selectedRowKeys: [], 


        // 表格
        tableLoading: false,
        dataSource: [],
        page: 1,
        pageSize: 10,
        search: {},
        totalCount: 1,
    }

    componentDidMount() {
        // 1578559045788 十三位时间戳
        // 当前时间戳与时间
        // const timeTtamp = moment(Date.now()).valueOf()
        // const currentTime = moment(timeTtamp).format("YYYY-MM-DD")

        // eslint-disable-next-line react/no-string-refs
        const { dispatch, home } = this.props
        if ( home.status ) {
            this.setState({
                tableLoading: true,
            })
            dispatch({
                type: 'home/getHome',
                payload: {}
            }).then(res => {
                // eslint-disable-next-line no-console
                console.log(this.props.home)
                // get data success.
                this.setState({
                    tableLoading: false,
                    dataSource: this.props.home.recordInformation.recordList
                })
            })
        } else {
            this.setState({
                dataSource: this.props.home.recordInformation.recordList
            })
        }

    }

    // 生成表头搜索
    getFields() {
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } }
        const { getFieldDecorator } = this.props.form
        const count = !!this.state.expand;
        if ( count ) {
            return (
                <>
                    <Col span={8}>
                        <Form.Item label="走访领导" {...formItemLayout}>
                            {getFieldDecorator("leader")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="走访街道" {...formItemLayout}>
                            {getFieldDecorator("street")(
                                <Select initialValue="请选择" placeholder="请选择">
                                    <Select.Option value="宝安街道">宝安街道</Select.Option>
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="走访时间" {...formItemLayout}>
                            {getFieldDecorator("date")(<DatePicker />)}
                            
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="企业名称" {...formItemLayout}>
                            {getFieldDecorator("name")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="机构代码" {...formItemLayout}>
                            {getFieldDecorator("code")(<Input placeholder="请输入" />)}
                        </Form.Item>
                    </Col>
                </>
            )
        } 
        return (
            <>
                <Col span={8} style={{display: 'block'}}>
                    <Form.Item label="走访领导" {...formItemLayout}>
                        {getFieldDecorator("leader")(<Input placeholder="请输入" />)}
                    </Form.Item>
                </Col>
                <Col span={8} style={{display: 'block'}}>
                    <Form.Item label="走访街道" {...formItemLayout}>
                        {getFieldDecorator("street")(
                            <Select initialValue="请选择" placeholder="请选择">
                                <Select.Option value="宝安街道">宝安街道</Select.Option>
                            </Select>
                        )}
                    </Form.Item>
                </Col>
            </>
        )
    }

    initfetch = () => {
        // 获取数据
    }

    // 新增走访记录弹窗
    showModal = () => {
        this.setState({ addVisible: true })
    }

    // 创建简讯弹窗
    showAddIntdModal = record => {
        console.log(record)
        const { form } = this.createFormRef.props
        form.resetFields()
        this.setState({ 
            addIntdVisible: true,
            introduceStatus: false,
            introduceKey: record.key,
        })
    }

    // 查看简讯弹窗
    showCheckIntdModal = record => {
        // 将record内容赋值给state.introduceDetails

        this.setState({ 
            introduceKey: record.key,
            checkIntdVisible: true,
            introduceDetails: record.introduceDetails
        })
    }

    // 编辑简讯弹窗
    showEditIntdModal = () => {
        const { introduceKey, dataSource } = this.state
        const { form } = this.createFormRef.props
        dataSource.forEach((val, index) => {
            if (val.key === introduceKey) {
                form.setFieldsValue({
                    ...dataSource[index].introduceDetails
                })
            }
        })
        // 改变introduceDetails
        // 改变introduceDetails
        this.setState({ checkIntdVisible: false, addIntdVisible: true, introduceStatus: true })
    }

    // 新增记录表单ref
    saveFormRef = formRef => {
        this.formRef = formRef
    }

    // 创建简讯表单ref
    createIntdFormRef = formRef => {
        this.createFormRef = formRef
    }

    // 所有弹窗取消
    handleCancel = () => {
        this.setState({ addVisible: false, addIntdVisible: false, confirmIntdVisible: false, checkIntdVisible: false })
    }

    // 创建or编辑简讯弹窗ok
    introduceCreate = () => {
        const { form } = this.createFormRef.props
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            const newContent = {
                ...values,
                key: 'niubi'
            }
            form.resetFields()
            // 改变introduceDetails
            this.setState({ 
                confirmIntdVisible: true,
                addIntdVisible: false,
                introduceDetails: newContent
            })
        })
    }

    // 确认简讯弹窗ok
    introduceConfirm = () => {
        // 确认introduceStatus 简讯状态是编辑还是创建
        // 编辑带key、introduceDetails
        // 创建带introduceDetails

        // 拿到introduceDetails内容
        const { introduceDetails, introduceKey, introduceStatus } = this.state
        const { dispatch, home } = this.props
        // dispatch introduceDetails
        // 上传introduceDetails

        // introduceStatus为true编辑
        if (introduceStatus) {
            // dispatch 编辑
            // introduceKey 编辑的key
            // introduceDetails 编辑的内容
            dispatch({
                type: 'home/editRecordIntroduce',
                payload: { introduceKey, introduceDetails, home }
            }).then(res => {
                if (res === 200) {
                    message.success('编辑成功！')
                    this.setState({ confirmIntdVisible: false, })
                }
            })
        } else {
            // introduceStatus为false添加
            // introduceKey 新增的key
            // introduceDetails 新增的内容
            dispatch({
                type: 'home/addRecordIntroduce',
                payload: { introduceKey, introduceDetails, home }
            }).then(res => {
                if (res === 200) {
                    message.success('创建成功！')
                    this.setState({ confirmIntdVisible: false, })
                }
            })
        }

    }

    // 新增走访记录弹窗ok
    handleCreate = () => {
        const { dispatch, home } = this.props
        const { form } = this.formRef.props
        form.validateFields((err, values) => {
            // console.log(values.f3.valueOf())
            // console.log(values.f3.format("YYYY-MM-DD"))
            if (err) {
                return;
            }
            
            values.date =  values.date.valueOf()
            dispatch({
                type: 'visitrecordandtable/addRecord',
                payload: values
            }).then(res => {
                console.log(res)
                if (res === 200) {
                    form.resetFields()
                    this.setState({ addVisible: false })
                    message.success('新增成功！')
                }
            })
            return;

            const newList = {
                ...values,
                number: '0',
                key: 'dsadsa',
                status: 0,
                numble: 0,
                createdAt: '',
                name: 'wa',
                code: '',
                follow: [],
                introduce: 0,
            }
            dispatch({
                type: 'home/addColRecordList',
                payload: { newList, home }
            }).then(res => {
                if (res === 200) {
                    form.resetFields()
                    this.setState({ addVisible: false })
                    message.success('新增成功！')
                }
            })
        })
    }

    // 收起展开
    toggle = () => {
        const { expand } = this.state
        this.setState({ expand: !expand })
    }

    // 搜索表查询
    handleSearch = e => {
        let originallyArrary = [...this.props.home.recordInformation.recordList]
        e.preventDefault()
        this.props.form.validateFields((err, values) => {
            // 日期转为字符串对比
            if (values.date) {
                // eslint-disable-next-line no-param-reassign
                values.date = values.date.format("YYYY-MM-DD")
            }
            Object.keys(values).forEach(key => {
                if (values[key]) {
                    const newBlank = []
                    if (key === 'date') {
                        originallyArrary.forEach((val, index) => {
                            if (moment(val[key]).format("YYYY-MM-DD").includes(values[key])) {
                                newBlank.push(originallyArrary[index])
                            }
                        })
                    } else {
                        originallyArrary.forEach((val, index) => {
                            if (val[key].includes(values[key])) {
                                newBlank.push(originallyArrary[index])
                            }
                        })
                    }
                    originallyArrary = newBlank
                }
            })
            this.setState({
                dataSource: originallyArrary
            })
        })
    }

    // 搜索表重置
    handleReset = () => {
        this.props.form.resetFields()
    }

    // 删除某行
    handleDelect = (_, record, index) => {
        const { dispatch, home } = this.props
        // eslint-disable-next-line react/no-access-state-in-setstate
        const newColums = JSON.parse(JSON.stringify(this.state.dataSource))
        newColums.forEach((val, index) => {
            if (val.key === record.key) {
                const keys = val.key
                dispatch({
                    type: 'home/delColRecordList',
                    payload: { keys, home }
                }).then(res => {
                    if (res === 200) {
                        newColums.splice(index, 1)
                        this.setState({
                            dataSource: newColums
                        })
                        message.success('删除成功！')
                    }
                })
            }
        })
    }

    // 表格选择
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys })
        console.log(selectedRowKeys)
    }

    // 表格清空
    onClearChange = () => {
        this.setState({ selectedRowKeys: [] })
    }

    // 导出报表
    exportExcel = () => {
        const { selectedRowKeys, dataSource } = this.state

        if (selectedRowKeys.length === 0) {
            message.info('请选择要导出的走访记录！')
            return;
        }
        const nowdata = []

        // eslint-disable-next-line array-callback-return
        selectedRowKeys.map(item => {
            dataSource.forEach((val, index) => {
                if (val.key === item) {
                    nowdata.push({
                        // 走访日期
                        date: moment(dataSource[index].date).format("YYYY-MM-DD"),
                        // 走访街道
                        street: dataSource[index].street,
                        // 企业名称
                        name: dataSource[index].name,
                        // 机构代码
                        code: dataSource[index].code,
                        // 走访领导
                        leader: dataSource[index].leader,
                        // 职务
                        job: dataSource[index].job,
                        // 随行人员
                        follow: dataSource[index].follow.join('、'),
                    })
                }
            })
            
        })
        
        // eslint-disable-next-line no-console
        const entozh = {
            "date":"走访日期",
            "street":"走访街道",
            "name":"企业名称",
            "code":"机构代码",
            "leader":"走访领导",
            "job":"职务",
            "follow":"随行人员",
          }

        const json = nowdata.map(item => {

            return Object.keys(item).reduce((newData, key) => {
                const newKey = entozh[key] || key
                newData[newKey] = item[key]
                return newData
            }, {})
        });
        const sheet = XLSX.utils.json_to_sheet(json);

        this.openDownloadDialog(this.sheet2blob(sheet,undefined), `走访记录信息.xlsx`);
    }

    sheet2blob = (sheet, sheetName) => {
        // eslint-disable-next-line no-param-reassign
        sheetName = sheetName || 'sheet1';
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项
  
        const wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        };
        const wbout = XLSX.write(workbook, wopts);
        const blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream"
        }); // 字符串转ArrayBuffer
        function s2ab(s) {
          const buf = new ArrayBuffer(s.length);
          const view = new Uint8Array(buf);
          // eslint-disable-next-line no-bitwise
          for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
          return buf;
        }
        return blob;
    }

    openDownloadDialog = (url, saveName) => {
        if (typeof url == 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        const aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        let event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }

    // 换页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize
        })
        // 获取数据
        this.initfetch()
    }

    render (){
        // 表格选择 rowSelection配置
        const { selectedRowKeys } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        }

        const RenderToolBar = () => (
            <div className={styles.toolBarBtn}>
                <Button icon="plus" type="primary" className={styles.plusCompany} onClick={this.showModal}>新增记录</Button>
                <Button icon="arrow-down" type="primary" className={styles.upCompany} onClick={this.exportExcel}>导出报表</Button>
                {/* <Button icon="arrow-up" type="primary" className={styles.upSMS}>导出简讯</Button> */}
            </div>
        )

        return (
            <PageHeaderWrapper title="走访记录表">
                <Card className={styles.proTable} bordered={false}>
                    <Form onSubmit={this.handleSearch} style={{padding: '12px 12px'}} className={styles.tableSerech}>
                        <Row gutter={24}>
                            {this.getFields()}
                            <Col span={8}>
                                <Form.Item style={{display: 'flex', justifyContent: 'center'}}>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                    <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                        重置
                                    </Button>
                                    <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
                                        {this.state.expand ? '收起' : '展开'} <Icon type={this.state.expand ? 'up' : 'down'} />
                                    </a>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                    <RenderToolBar />
                    <div style={{margin: '0 24px',marginBottom: '16px'}}>
                        <div
                            style={{
                                backgroundColor: '#e6f7ff',
                                border: '1px solid #91d5ff',
                                display: 'flex',
                                padding: '10px 20px',
                                borderRadius: '5px',
                                width: '100%',
                                position: 'relative'
                            }}>
                                <i><IconFont type="icon-gantanhao" style={{ fontSize: '16px', marginRight: '10px'}} /></i>
                                <div style={{fontWeight: 'bold'}}>
                                    已选择<span style={{color: '#1890ff', padding: '0 5px'}}>{this.state.selectedRowKeys.length}</span>项
                                </div>
                                <a style={{fontWeight: 'bold', position: 'absolute', right: '15px'}} onClick={this.onClearChange}>
                                    清空
                                </a>
                        </div>
                    </div>
                    {/* <Table
                        rowKey="key"
                        loading={this.state.tableLoading}
                        dataSource={this.state.dataSource}
                        columns={this.state.columns}
                        rowSelection={rowSelection}
                        pagination={{
                            defaultPageSize: 10,
                            showQuickJumper: true,
                            showSizeChanger: true
                        }}
                    >
                    </Table> */}
                    <PublicTableWrapper
                        loading={this.state.tableLoading}
                        columns={this.state.columns}
                        data={this.state.dataSource}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange= {(page, pageSize) => this.paginationChange(page, pageSize)}
                        rowSelection={rowSelection}
                    />
                </Card>


                <AddRecord
                    wrappedComponentRef={this.saveFormRef}
                    visible={this.state.addVisible}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                />

                <CreateIntroduce 
                    wrappedComponentRef={this.createIntdFormRef}
                    visible={this.state.addIntdVisible}
                    onCancel={this.handleCancel}
                    onCreate={this.introduceCreate}
                />

                <ConfirmIntroduce 
                    visible={this.state.confirmIntdVisible}
                    onCancel={this.handleCancel}
                    onCreate={this.introduceConfirm}
                    content={this.state.introduceDetails}
                />

                <CheckIntroduce 
                    visible={this.state.checkIntdVisible}
                    onCancel={this.handleCancel}
                    onEdit={this.showEditIntdModal}
                    content={this.state.introduceDetails}
                />

            </PageHeaderWrapper>
        )
    }
}
const WrappedDynamicFieldSet = Form.create()(Management);

export default WrappedDynamicFieldSet